Module# 04: Arrays Lecture#12: Programming
for Arrays
// Example 12.1:
Demonstration of 1D array
/* Demonstration of a
one-dimensional array */
class Array {
public static void main(String args[]) {
int month[];
month = new int[12];
month[0] = 31;
month[1] = 28;
month[2] = 31;
month[3] = 30;
month[4] = 31;
month[5] = 30;
month[6] = 31;
month[7] = 31;
month[8] = 30;
month[9] = 31;
month[10] = 30;
month[11] = 31;
System.out.println("April has " + month[3] + " days.");
}
}
// Example 12.2:
Simple examples of creating arrays
/* The following
program shows the different ways that an array can be declared and initialized.
*/
public class ArrayDefinitionDemo {
public static void main(String[] args) {
float x[];
x = new float[100];
args = new String[10];
boolean[] isPrime = new boolean[1000];
int fib[] = {0, 1, 1, 2, 3, 5, 8, 13};
short[][][] b = new short[4][10][5];
double a[][] = {{1.1,2.2}, {3.3,4.4}, null, {5.5,6.6}, null};
a[4] = new double[66];
a[4][65] = 3.14;
Object[] objects = {x, args, isPrime, fib, b, a};
}
}
// Example 12.3:
Initialization of a 1D array with user input from keyboard
class
ArrayInitializationDemo {
int a = new int [100]; // Declaring a 1D
array of size 100
int size; // Actual size of the array
void loadArray() { // Actual size of the
array
Scanner in = new Scanner(System.in); // To read from keyboard
System.out.println(“Enter size < 100”);
size = in.nextInt(); // read a number
for(int i = 0;i<size;i++){
System.out.println("Enter "+ (i+1) + "th number ");
a[i] = in.nextInt(); // Load the i-th entry
}
System.out.println(“Length = “ + a.length);
System.out.println(a); // Display the array
on the screen
}
}
// Example 12.4:
Initialization of a 1D array with random numbers
/* This program will
initialize an array of a given size within a range between MIN and Max.*/
import java.util.*;
class
ArrayInitializationRandomDemo {
int a = new int [100];
// Declaring a 1D array of size 100
int size; // Actual size of the array
int MIN = 1, MAX = 100; // Range of the
numbers
int generateRandom(int min, int max) { // Generating a random number
int rand = (int)(Math.random() * ((max - min) + 1)) + min;
return rand;
}
public static void main (String args[] {
Scanner in = new Scanner(System.in); // To read the size from the user
System.out.println(“Enter size < 100”);
size = in.nextInt(); // read a number from
the keyboard
for(int i = 0;i<size;i++){
a[i] = generateRandom(MIN, MAX); // Generate and return a random number
}
System.out.println(“Capacity = “ + a.length + “Size: = “+ size);
System.out.println(a); // Display the array
on the screen
}
}
// Example 12.5:
Printing and duplicating a 1D array
/* This program will
print on the screen using a declared print method and duplicate an array. */
public class PrintingArrays {
// Defining a static method to print an array
of integer type
public static void print(int[] a) {
System.out.printf("{%d", a[0]);
for (int i = 1; i < a.length; i++) {
System.out.printf(", %d", a[i]);
}
System.out.println("}");
}
// The following is an overloaded method to
print data of any type
public static void print(Object[] a) {
System.out.printf("{%s", a[0]);
for (int i = 1; i < a.length; i++) {
System.out.printf(", %s", a[i]);
}
System.out.println("}");
}
// Defining the main
method
public static void main(String[] args) {
int[] a = {22, 44, 66, 88}; // Create an array of
integers
print(a);
int[] b = (int[])a.clone(); // duplicate a[] in
b[]
print(b);
String[] c = {"AB", "CD", "EF"}; // Create an array of strings
print(c);
String[] d = (String[])c.clone(); // duplicate c[] in
d[]
print(d);
c[1] = "XYZ"; // change c[], but
not d[]
print(c);
print(d);
}
}
// Example 12.6:
Reversing a 1D array using a recursive method
/* This program shows
how an existing array can be reversed its ordering: A genetic programming using
recursion is illustrated. */
public class Generic1DArray <T> {
private T x; // x is a collection of generic type T
// Constructor
public Generic1DArray(T t) {
x = t;
}
// A recursive method to reverse the ordering
of array x
public void reverse1D(int length) {
if(length > 1) { // Termination
condition check
//
Swap the end elements
T temp;
temp=x[size–length];
x[size–length]=x[length-1];
x[length-1]=temp;
reverse1D(length-1); // Do recursively for
the next level
}
} // This completes the
definition of the generic class GeneriClass<T>
/* The main program
is given below. */
public class
Generic1DArrayRecursionDemo {
public static void main (String args []) {
// Case 1: Working with integer array
Generic1Darray<Integer> intA = new Generic1Darray<Integer> (1, 2, 3, 4, 5, 6);
intA.reverse1Darray(6); // Reversing the array intA
System.out.println(intA); // Print the result
// Case 2: Working
with String array
Generic1Darray<String> stringA = new Generic1Darray<String> (“A”, “E”, “I”, “O”, “U”);
stringA.reverse1Darray(5); // Reversing the array stringA
System.out.println(stringA); // Print the result
}
} // This completes the definition of the main
class
// Example 12.7:
Insertion into a 1D array
/* This program shows
how an item can be inserted into an existing array. */
import java.util.*;
public class Insertion1DArray {
int a[100]; // An integer array
with default 100 capacity
int size=0; // The number of
items present
public void static create(int size) {// Initialize the array
if(size > 100) {
System.out.println(“Could not initialize…”);
return 0;
}
this.size = size;
Scanner in = new Scanner(System.in); // To read from keyboard
for(int i = 0;i<size;i++){ // Reading the number
System.out.println("Enter "+ (i+1) + "th number ");
a[i] = in.nextInt(); // Load the i-th entry
}
System.out.println(“Capacity = “ + a.length + “Size + “ + size);
System.out.println(a); // Display the array on the screen
}
// Continued on ...
public void static insert(int loc) {// Insertion at loc of the array
if(size == a.length) {
System.out.println(“Array is overflow: Insertion fails…”);
return 0;
}
if ((loc < 0) || (loc > size)){
System.out.println(“Out of range: Insertion fails…”);
return 0;
}
Scanner in = new Scanner(System.in); // To read from keyboard
int item = in.nextInt();
for(int i = size;i< loc;i--) // Shifting operation
a[i+1] = a[i]; // Shift to right one
place
a[loc] = item;
System.out.println(“Capacity = “ + a.length + “Size + “ + size);
System.out.println(a); // Display the array
on the screen
}
/* The main method ...
public void static main (String args[]){
Scanner in = new
Scanner(System.in); // To read from
keyboard
System.out.println(“Enter the number of
elements : “);
int n = in.nextInt();
create(n);
System.out.println(“Enter the new number
to be inserted: “);
n = in.nextInt();
System.out.println(“At position? “);
int pos = in.nextInt();
insert(n, pos);
System.out.println(“Capacity = “ +
a.length + “Size + “ + size);
System.out.println(a); // Display the array on the screen
}
}
// Example 12.8:
Deletion from a 1D array
/* This program shows
how an item can be deleted from an existing array. */
import java.util.*;
public class Deletion1DArray {
int a[100]; // An integer array
with default 100 capacity
int size=0; // The number of
items present
public void static create(int size) {// Initialize the array
if(size > 100) {
System.out.println(“Could not initialize…”);
return 0;
}
this.size = size;
Scanner in = new Scanner(System.in); // To read from keyboard
for(int i = 0;i<size;i++){ // Reading the number
System.out.println("Enter "+ (i+1) + "th number ");
a[i] = in.nextInt(); // Load the i-th entry
}
System.out.println(“Capacity = “ + a.length + “Size + “ + size);
System.out.println(a); // Display the array on the screen
}
public void static delete(int loc) {// Deletion of the item at loc position
if(size == 0) {
System.out.println(“Array is underflow: No item to delete!”);
return 0;
}
if ((loc < 0) || (loc > size)){
System.out.println(“Out of range: Deletion fails ...”);
return 0;
}
int item = a[loc]; // The item at loc
for(int i = loc;i < size;i++) // Shifting operation
a[i] = a[i+1]; // Shift to left one
place
a[size] = NULL;
size--;
System.out.println(“Capacity = “ + a.length + “Size + “ + size);
System.out.println(a); // Display the array
on the screen
}
/* The main method */
public void static main (String args[]){
Scanner in = new Scanner(System.in); // To read from keyboard
System.out.println(“Enter the number of elements : “);
int n = in.nextInt();
create(n);
System.out.println(“Enter the position from number to be deleted: “);
int pos = in.nextInt();
int item = delete(pos);
System.out.println(“Deleted item: “ + item);
System.out.println(“Capacity = “ + a.length + “Size + “ + size);
System.out.println(a); // Display the array
on the screen
}
}
// Example 12.9:
Creating a 2D array
/* This program shows
how a 2D array of integers can be created, initialized and
displayed both in
row-major and column major orders. */
import java.util.*;
public class TwoDarray {
int a[][]; // Declared that a is
an array of two-dimensional
int row; // The number of rows
int col; // The number of
columns
TwoDarray(int row, int col) {
a = new int[row[col];
this.row = row; this.col = col;
}
public void initialize() {
Scanner in = new Scanner(System.in);
for(int i = 0; i < row, i++){
for(int j = 0; j < col,; j==) {
System.out.println("Enter a[%d][%d] :" + i + j);
a[i][j] = in.nextInt();
}
}
}
// Display the matrix in Row-Major order
public void printRowMajor() {
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
System.out.print(a[i][j]);
}
System.out.println(" ");
}
}
// Display the matrix in Column-Major order
public void printColMajor() {
for(int i=0;i<col;i++){
for(int j=0;j<row;j++){
System.out.print(a[j][i]);
}
System.out.println(" ");
}
}
// Defining a method
for 2D matrix addition
public int[][] addition(int b[][]) {
// First check if the two matrices are
conformable for addition
if(this.row != b.row) && (this.col != b.col) {
System.out.println("Error! Matrix are not of proper
size.");
return (0);
else {
twoDarray c = new twoDarray[row][col]; // Declare a the output matrix
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
c[ij[j] = this.[i][j] + b[i][j];
return(c);
}
}
// Defining a method
for 2D matrix multiplication
public int[][] multiplication(int b[][]) {
// First check if the two matrices are
conformable for multiplication
if(this.col != b.row) {
System.out.println("Error! Matrices are not of proper
size.");
return (0);
else {
twoDarray c = new twoDarray[row][b.col]; // Declare the output matrix
for(int i = 0; i < row; i++)
for(int j = 0; j < b.col; j++) {
c[i][j] = 0;
for(int k = 0; k < b.row; k++){
c[ij[j] = c[i][j] + this.[i][k] * b[k][j];
}
return(c);
}
}
} // End of the
twoDarray class definition
// The main program
showing different matrix operations
class
twoDarrayAdditionDemo {
public static void main {String args [] {
twoDarray x = new TwoDarry(3,4); // Create a 2D array of 3x4
x.initialize();
//
Initialize the array
twoDarray y = new TwoDarry(3,4); // Create a 2D array of 3x4
y.initialize();
//
Initialize the array
twoDArray z[][];
z = x.addition(y);
// Do addition of two matrix
z.printRowMajor(); // Print the array in row-major order
z = x.multiplication(y); // Do multiplication of two matrix
z.printRowMajor(); // Print the array in row-major order
}
}